//
//  BoozeDetailsViewController.m
//  VeganIsEasy
//
//  Created by Matthew Feinberg on 5/30/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "BoozeDetailsViewController.h"
#import <SystemConfiguration/SystemConfiguration.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <net/if.h>
#include <ifaddrs.h>
#import <sys/socket.h>

@implementation BoozeDetailsViewController

@synthesize notesWebView;

- (id)initWithVendorId:(NSInteger)primaryKey database:(sqlite3 *)db {
	if (self = [super initWithNibName:@"BoozeDetails" bundle:nil]) {
		vendorId = primaryKey;
		database = db;
	}
	return self;
}

/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	[super viewDidLoad];

	[notesWebView setDelegate:nil];
	[notesWebView setDelegate:self];
	
	char *sql = "SELECT vendor, category, short_notes, notes FROM booze_vendor WHERE booze_vendor_id=?";
	sqlite3_stmt *statement = nil;
	if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK) {
		sqlite3_bind_int(statement, 1, vendorId);
		if (sqlite3_step(statement) == SQLITE_ROW) {
			vendorLabel.text = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
			categoryLabel.text = [[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)] capitalizedString];
			shortNotesLabel.text = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)];
			NSString * notes = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 3)];
			[notesWebView loadHTMLString:notes baseURL:[NSURL URLWithString:@"http://www.barnivore.com/"]];
			
			
			
			// Set the icon
			NSString *shortNotes = shortNotesLabel.text;
			BOOL notVegan = [[shortNotes lowercaseString] rangeOfString:@"not vegan"].location != NSNotFound;
			BOOL someVegan = ![[shortNotes lowercaseString] isEqual:@"vegan friendly"];
			NSString *category = [categoryLabel.text lowercaseString];			
			NSString *iconName = nil;
			if (notVegan) {
				iconName = [NSString stringWithFormat:@"%@_not_vegan_icon.png",category];
			}
			else if (someVegan) {
				iconName = [NSString stringWithFormat:@"%@_some_vegan_icon.png",category];
			}
			else {
				iconName = [NSString stringWithFormat:@"%@_vegan_icon.png",category];
			}
			
			categoryImageView.image = [UIImage imageNamed:iconName];
			
/*			
			NSString *category = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];
			if ([category isEqualToString:@"wine"]) {
				categoryImageView.image = [UIImage imageNamed:@"wine.png"];
			}
			else if ([category isEqualToString:@"liquor"]) {
				categoryImageView.image = [UIImage imageNamed:@"liquor.png"];
			}
 */
		}
	}
	sqlite3_finalize(statement);
	
//	[vendorLabel setText:vendor];
//	[categoryLabel setText:@"beer"];
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
/*	
	NSString *searchTerm = [searchBar text];
	[self handleSearchForTerm:searchTerm];
	[search resignFirstResponder];
*/ 
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchTerm
{
	/*
	int length = [[searchTerm stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length];
	
	if (length == 0 || searchTerm == nil)
	{	 
		[self resetSearch];
		// table is my UITableView IBOutlet declared in the interface
		[table reloadData];
		return;
	}
	[self handleSearchForTerm:searchTerm];
	 */
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
	/*
	search.text = @"";
	[self resetSearch];
	[table reloadData];
	[searchBar resignFirstResponder];
	*/ 
}

// Direct from Apple. Thank you Apple
- (BOOL)addressFromString:(NSString *)IPAddress address:(struct sockaddr_in *)address
{
    if (!IPAddress || ![IPAddress length]) return NO;
	
    memset((char *) address, sizeof(struct sockaddr_in), 0);
    address->sin_family = AF_INET;
    address->sin_len = sizeof(struct sockaddr_in);
	
    int conversionResult = inet_aton([IPAddress UTF8String], &address->sin_addr);
    if (conversionResult == 0) {
		NSAssert1(conversionResult != 1, @"Failed to convert the IP address string into a sockaddr_in: %@", IPAddress);
        return NO;
    }
	
    return YES;
}

- (NSString *) getIPAddressForHost: (NSString *) theHost
{
	struct hostent *host = gethostbyname([theHost UTF8String]);
    if (!host) {herror("resolv"); return NULL; }
	struct in_addr **list = (struct in_addr **)host->h_addr_list;
	NSString *addressString = [NSString stringWithCString:inet_ntoa(*list[0]) encoding:NSUTF8StringEncoding];
	return addressString;
}

- (BOOL) hostAvailable: (NSString *) theHost
{
	
    NSString *addressString = [self getIPAddressForHost:theHost];
    if (!addressString)
    {
        printf("Error recovering IP address from host name\n");
        return NO;
    }
	
    struct sockaddr_in address;
    BOOL gotAddress = [self addressFromString:addressString address:&address];
	
    if (!gotAddress)
    {
		printf("Error recovering sockaddr address from %s\n", [addressString UTF8String]);
        return NO;
    }
	
	SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&address);
    SCNetworkReachabilityFlags flags;
	
	BOOL didRetrieveFlags =SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);
	
    if (!didRetrieveFlags)
    {
        printf("Error. Could not recover network reachability flags\n");
        return NO;
    }
	
    BOOL isReachable = flags & kSCNetworkFlagsReachable;
    return isReachable ? YES : NO;;
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
	//NSLog(@"expected:%d, got:%d", UIWebViewNavigationTypeLinkClicked, navigationType);
	if (navigationType == UIWebViewNavigationTypeLinkClicked) {
		//if ([[[request URL] absoluteString] rangeOfString:@"mailto:"].location != NSNotFound) {
		if ([[[[request URL] scheme] lowercaseString] isEqual:@"mailto"]) {
			//[[UIApplication sharedApplication] openURL:[NSString stringWithFormat:@"mailto:%@",[[request URL] absoluteString]]];
//			[[UIApplication sharedApplication] openURL:[NSString stringWithFormat:@"mailto:%@",[[request URL] absoluteString]]];
//			[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"mailto://info@iphonedevelopertips.com"]];
//			return YES;
			[[UIApplication sharedApplication] openURL:[request URL]];
		}
		else {
			if ([self hostAvailable:[[request URL] host]]) {
				[[UIApplication sharedApplication] openURL:[request URL]];
			}
			else {
				UIAlertView *someError = [[UIAlertView alloc] initWithTitle: @"Network error" message: @"The page can not be opened, because you are not connected to the Internet." delegate: self cancelButtonTitle: @"Ok" otherButtonTitles: nil];
				[someError show];
				[someError release];
			}
		}
		return NO;
	}
	
	return YES;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
	//UIAlertView *someError = [[UIAlertView alloc] initWithTitle: @"Network error" message: @"Error sending your info to the server" delegate: self cancelButtonTitle: @"Ok" otherButtonTitles: nil];
	//[someError show];
	//[someError release];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}


- (void)dealloc {
	[notesWebView setDelegate:nil];
	[vendorLabel release];
	[categoryLabel release];
	[shortNotesLabel release];
	[notesWebView release];
	[categoryImageView release];
	[vendor release];
	[super dealloc];
}


@end
